package com.exam.controller.login;

import javax.servlet.http.HttpSession;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.exam.common.vo.ExamStuVO;
import com.exam.common.vo.ExamTeacherVO;
import com.exam.service.student.StuService;
import com.exam.service.teacher.TeacherService;

@Controller
public class LoginController {

	private Logger log = LogManager.getLogger(LoginController.class);
	
	@Autowired
	TeacherService teaService;

	@Autowired
	StuService stuService;

	@RequestMapping(value = { "/", "/home" }, method = RequestMethod.GET)
	public String login(Model model) {
		log.info("----info-----");
		log.debug("----debug----");
		log.error("----error-----");
		model.addAttribute("stuVO", new ExamStuVO());
		
		return "/sign/login";
	}

	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String login(ExamStuVO sVO, String speed, HttpSession session, Model model) {
	
		ExamTeacherVO teacherVO = teaService.findByTeaNumber(Integer.parseInt(sVO.getExamStuNumber()));
		ExamStuVO stuVO = stuService.findByStuNumber(sVO.getExamStuNumber());
		if (speed.equals("teacher")) {
			if (this.isTea(teacherVO, sVO.getExamStuPassword())) {
				session.setAttribute("teacher", teacherVO);
				return "redirect:/stu/stuList";
			}
		} else if (speed.equals("student")) {
			if (this.isStu(stuVO, sVO.getExamStuPassword())) {
				session.setAttribute("stuVO", stuVO);
				return "redirect:/subject/subjectList";
			}
		} 
		model.addAttribute("stuVO", sVO);
		model.addAttribute("message", "用户名或密码错误");
		return "/sign/login";
	}

	public boolean isStu(ExamStuVO stuVO, String password) {
		boolean isStu = true;
		if (stuVO == null) {
			isStu = false;
		} else {
			if (!password.equals(stuVO.getExamStuPassword())) {
				isStu = false;
			}
		}
		return isStu;
	}

	public boolean isTea(ExamTeacherVO teaVO, String password) {
		boolean isTea = true;
		if (teaVO == null) {
			isTea = false;
		} else {
			if (!password.equals(teaVO.getExamTeacherPassword())) {
				isTea = false;
			}
		}
		return isTea;
	}

	@RequestMapping(value = "/logout")
	public String logout(HttpSession session, Model model) {
		model.asMap().remove("teacher");
		session.invalidate();
		return "redirect:/home";
	}
}
